package com.PopulateDB;

import java.util.Calendar;

public class Populate {
	private static MySQLDBPopulator db = null;
	
	public Populate(PopulateFormat thingType, int noOfThings){
		int minTimeEstimateThreshold = 2000;
		int timeEstimateInserts = 1000;
		
		// Connect to the database
		db = new MySQLDBPopulator("fakefile");
		
		// If we manage to delete and recreate the table then we can insert the things
		if(thingType.remakeTable(db)){
			/*
			 * If we are inserting a lot of things then we'll estimate the time taken by taking an insert sample
			 */
			if(noOfThings > minTimeEstimateThreshold){
				Calendar cal = Calendar.getInstance();
				long startTime = cal.getTimeInMillis();
				
				for(int i=1; i <= timeEstimateInserts; i++){
					thingType.makeThing(db, i);
				}
				
				cal = Calendar.getInstance();
				
				System.out.println("Estimated time remaining: " + (((cal.getTimeInMillis()-startTime)/1000.0) * ((noOfThings-timeEstimateInserts)/(1.0 * timeEstimateInserts))) + " seconds");
			}
			else
				timeEstimateInserts = 0;
			
			/*
			 * Now we will insert the remained of the things
			 */
			System.out.print("Progress: " + timeEstimateInserts);

			for(int i=timeEstimateInserts+1; i <= noOfThings; i++){
				thingType.makeThing(db, i);
				
				if(i%1000 == 0) System.out.print(" " + i);
				if(i%15000 == 0) System.out.print("\n\t");
			}
			
			System.out.println(" : total = " + noOfThings);
			
		}
		else{
			System.out.println("Populater: We could not drop and recreate the table");
		}
		
		// Clean up
		db.closeConnection();
	}
}
